'''
https://leetcode.cn/problems/ternary-expression-parser
'''


class Solution:
    def parseTernary(self, s: str) -> str:
        stack = []
        i = len(s) - 1
        while i >= 0:
            if s[i] == '?':
                flag = s[i - 1] == 'T'
                i -= 1
                true_v = stack.pop()
                stack.pop()
                false_v = stack.pop()
                stack.append(true_v if flag else false_v)
            else:
                stack.append(s[i])
            i -= 1
        return stack[0]
